/**
 * 业务表单基础的增、删、改、查
 */
import {
  init,
  list,
  del
} from "@/views/youshuda/api/BaseApi";
import {getToken} from "@/utils/auth";

export const TableMixins = {
  components: {
    FormItem: () => import('@/views/youshuda/components/FormItem/index'),
    Edit: () => import('@/views/youshuda/components/FormEdit/index')
  },
  computed: {
    /**
     * 过滤表格中需要显示的字段
     */
    listShowColumnFilter() {
      let that = this;
      //过滤满足显示的字段信息
      return this.fieldInfo.filter((column, index, self) => {
        return column.isList == '1'
      });
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      //表格的ref
      tableRef: 'tables',
      // 选中数组
      ids: [],
      // 当前编辑ID
      updateId: '',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 数据表格信息
      table: {
        //表格高度
        tabHeight: 0,
        _tabHeight: 0,
        // 总条数
        total: 0
      },
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示流程发起对话框
      procOpen: false,
      // 流程组件参数
      ProcParams: {},
      // 字段信息
      fieldInfo: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        timeParams: {}
      },
      //表格数据
      tableData: [],
      //判断当前模块是否启用流程
      isEnabledProc: '0',
      //加载类型
      initType: '',
      //业务模块访问配置
      visitConfig: null,
      //业务模块生成ID
      tabGenId: '',
      //业务模块配置信息
      modeConfig: {},
      //API前缀
      prefixUrl: '',
      //表单设计Key
      formBuildKey: '',
      //组件描述
      componentDesc: '',
      //数据导入配置
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 标记是否正在上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: '',
      },
      //优树搭业务流程进度配置信息
      mksFlowConfig: {
        title: "流程进度",
        taskUuid: "",
        isOpen: false
      }
    }
  },
  created() {
    /** 初始化业务模块参数 **/
    this.initModeParams();
  },
  methods: {
    /** 初始化业务模块参数 **/
    initModeParams() {
      //业务模块生成ID
      this.tabGenId = this.$route.params.tabGenId;
      this.visitConfig = {
        "tableId": this.tabGenId,
        "genType": this.strIsNotEmpty(this.tabGenId) ? "2" : "1",
        "baseUrlPrefix": this.prefixUrl
      }
      let matcheds = this.$route.matched.filter(item => item.meta && item.meta.title)
      if(matcheds){
        let nowMeta = matcheds[matcheds.length-1]
        this.componentDesc = nowMeta.meta.title
      }
      /** 初始化字段信息 **/
      this.initField()
    },
    /** 初始化字段信息 **/
    initField() {
      if (this.strIsEmpty(this.tabGenId) && this.strIsEmpty(this.prefixUrl)) {
        console.log("模块请求路径或模块ID为空，中止加载...");
        return;
      }
      init(this.tabGenId, this.prefixUrl).then(res => {
        if (res.code == 200) {
          let config = res.data;
          if (config == null || config == undefined) {
            this.msgError('获取配置信息失败')
            return;
          }
          this.modeConfig = config;
          if (this.strIsNotEmpty(this.tabGenId)) {
            //API前缀
            this.prefixUrl = config.prefixUrl
            //表单设计Key
            this.formBuildKey = config.formBuildKey
            //组件描述
            if(this.strIsEmpty(this.componentDesc )){
              this.componentDesc = config.componentDesc
            }
          }
          this.initLoadData(config.fieldInfos);
        } else {
          this.msgError(res.msg)
        }
      })
    },
    /** 加载字段 **/
    initLoadData(fieldInfo) {
      this.fieldInfo = fieldInfo
      fieldInfo.forEach(item => {
        //查询参数
        this.queryParams[item.columnName] = null
      })
      /** 获取列表数据 **/
      this.getList()
    },
    /** 查询列表数据 */
    getList() {
      this.loading = true
      //清空当前数据
      this.tableData = []
      //请求数据
      list(this.tabGenId, this.prefixUrl, this.queryParams).then(response => {
        this.tableData = response.rows
        let total = response.total
        if (!(total instanceof Number)) {
          total = Number(total)
        }
        this.table.total = total
        this.loading = false
        // 重置数据表格的高度
        this.resetTableHeight()
      })
    },
    /** 更新快速设置后的信息 **/
    changeModeConfig(modeConfig) {
      this.modeConfig = modeConfig;
    },
    /** 表单同步数据 **/
    ItemValChange(data) {
        this.queryParams[data.key] = data.val
    },
    /** 取消按钮 **/
    cancel(param) {
      this.updateId = ''
      this.open = false
      this.procOpen = false;
      if (param != undefined && param.isRef == true) {
        this.getList()
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置查询表单信息 **/
    resetQuery() {
      this.queryParams['timeParams'] = {}
      this.fieldInfo.forEach((item, index) => {
        this.$set(this.fieldInfo[index], 'fieldData', null)
        this.queryParams[item.columnName] = null
      })
      this.handleQuery()
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.defPk)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.updateId = ''
      this.open = true
      this.title = '添加' + this.componentDesc
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if(this.ids.length>1){
        this.msgError('修改数据不支持勾选多条记录')
        return;
      }
      this.updateId = row.defPk || this.ids;
      this.open = true
      this.title = '修改' + this.componentDesc
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var that = this;
      const ids = row.defPk || this.ids;
      this.$confirm('是否确认删除勾选数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return del(that.tabGenId, that.prefixUrl, ids);
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 下载模板操作 */
    importTemplate() {
      let url = this.prefixUrl + '/importTemplate'
      if (this.strIsNotEmpty(this.tabGenId)) {
        url = '/common/basemode/importTemplate/' + this.tabGenId
      }
      this.download(url, {
        ...this.queryParams
      }, `${this.componentDesc + '_模块'}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      if (this.strIsNotEmpty(this.tabGenId)) {
        this.upload.url = process.env.VUE_APP_BASE_API + "/common/basemode/importData/" + this.tabGenId
      }
      this.upload.title = this.componentDesc;
      this.upload.open = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this;
      const queryParams = JSON.parse(JSON.stringify(this.queryParams));
      queryParams['pageSize'] = 20000;
      let url = this.prefixUrl + '/export'
      if (this.strIsNotEmpty(this.tabGenId)) {
        url = '/common/basemode/export/' + this.tabGenId
      }
      this.$confirm('是否确认导出当前查询结果所有数据，最多可导出20000条数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        that.download(url, {
          ...queryParams
        }, `${that.componentDesc + '_' + new Date().getTime()}.xlsx`)
      })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "处理结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    handleFileError(err, file, fileList) {
      console.log(err);
      console.log(file);
    },
    // 提交上传文件
    submitFileForm() {
      //执行上传
      this.$refs.upload.submit();
    },
    // 取消上传文件
    cancelFileForm() {
      this.upload.open = false
      this.$refs.upload.clearFiles();
    },
    // 重置数据表格的高度
    resetTableHeight() {
      this.$nextTick(() => {
        this.table.tabHeight = this.table._tabHeight
        if (this.showSearch) {
          /**
           * 显示搜索区域时
           */
          this.table.tabHeight = this.table._tabHeight - this.$refs.queryForm.$el.offsetHeight
        }
        // 重新渲染表格
        try{
          this.$refs[this.tableRef].doLayout();
        }catch (e){}
      })
    },

  },
  beforeMount() {
    /** 适配数据表格高度 **/
    this.table._tabHeight = this.appMain.height - 130
  },
  // 页面缓存重新进入页面时，在路由组件被激活时触发
  activated() {
    this.$nextTick(() => {
      this.$refs[this.tableRef].doLayout(); // 对表格重新布局（解决切换页面后列错乱）
    })
  },

  watch: {
    /** 监听查询输入是否显示，适配数据表格高度 **/
    showSearch: {
      immediate: true,
      handler(nowdata) {
        this.resetTableHeight();
      }
    }

  }
}
